package com.google.donutrush;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Entities.User;
import Services.UserService;
import Services.UserServiceDBimpl;

import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

public class FacebookauthorizationServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		//we use this class instance to insert the user and the score to a DB, as for now the DB is lists in the memory...
		UserService us = UserServiceDBimpl.getInstance();
		
		//Prepare the json object we create from the request body
		JSONObject jsonObject = null;
		//The object comes in the body as the key in the first element of the ParameterMap (im not sure why)
		//I only converted it to array because I like it better
		Object[] m = request.getParameterMap().keySet().toArray();
		//Create the json from the object in m[0]
		try {
			jsonObject = new JSONObject(m[0].toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		
		//getting all filled params in the registration form of the json object
		String fbid = "";

		try {
			fbid = (String) jsonObject.get("facebookID");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		
		
		JSONObject newJsonObject = new JSONObject();
		String error = "Denied";
		
		// check if user exists in DB
		if ((fbid.equals(""))){
			try {
				newJsonObject.put("result", error);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			User user = us.getUserByFBid(fbid);
			if ((user != null) && (user.getFbID().equals(fbid))){
				//int bestScore = user.getBestScore();
				try {
					//newJsonObject.put("nick", name);
					//newJsonObject.put("best-score", bestScore);
					newJsonObject.put("result", "Confirmed");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				try {
					newJsonObject.put("result", error);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		response.setContentType("text/plain");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String myString = newJsonObject.toString();
		writer.println(myString);
		writer.close();
	}
	
}
